#include "CZMotionRemoteAdapter.h"
#include "utility/GameMsg.h"

namespace RemoteUtility
{
	namespace RemoteAdapter{
		CZMotionRemoteAdapter::CZMotionRemoteAdapter(IMessageShower* msgBox) 
			: IRemoteAdapter()
			, m_pMessageShower( msgBox )
		{
			//init the two parameter
			m_errCode = CheckRemoteDriver();
		}

		E_ZMotion_ErrorCode CZMotionRemoteAdapter::CheckRemoteDriver()
		{
			if ( m_pMessageShower )
				m_pMessageShower->ShowMessageBox( GameUtility::IMessageBox::E_MESSAGE_WAITING );

			checkDriverHelper();

			if ( m_pMessageShower )
				m_pMessageShower->HideMessageBox( GameUtility::IMessageBox::E_MESSAGE_WAITING );

			return m_errCode;
		}

		bool CZMotionRemoteAdapter::DoSearching(){
			bool result = false;
			return result;
		}

		bool CZMotionRemoteAdapter::DoStopSearching(){
			bool result = false;
			return result;
		}

		bool CZMotionRemoteAdapter::DoInstall(){
			bool result = false;

			if ( m_MSDriver.InstallDriver() )
			{
				result = true;
				m_bDriverInstalled = true;
			}

			checkDriverHelper();

			return result;
		}

		bool CZMotionRemoteAdapter::DoUninstall(){
			bool result = false;

			if ( m_MSDriver.UnInstallDriver() )
			{
				result = true;
				m_bDriverInstalled = false;
			}

			checkDriverHelper();

			return result;
		}

		void CZMotionRemoteAdapter::setErrorCode(E_ZMotion_ErrorCode ec)
		{
			m_errCode = ec;
			switch (m_errCode)
			{
			case E_NOERROR:
				IRemoteAdapter::m_bDriverInstalled = true;
				IRemoteAdapter::m_bUSBConnected = true;
				break;
			case E_USB_NOT_CONNECTED:
				IRemoteAdapter::m_bDriverInstalled = true;
				IRemoteAdapter::m_bUSBConnected = false;
				break;
			case E_DRIVER_NOT_INSTALLED:
				IRemoteAdapter::m_bDriverInstalled = false;
				IRemoteAdapter::m_bUSBConnected = false;
				break;
			default:
				break;
			}
		}
		void CZMotionRemoteAdapter::checkDriverHelper()
		{
			m_errCode = E_NOERROR;

			// Check driver
			BOOL bOpenFilter = m_MSDriver.Open_Filter();
			m_bDriverInstalled = (TRUE == m_MSDriver.IsInstalledDriver());
			m_bUSBConnected = (TRUE == m_MSDriver.IsOpened());

			if ( !bOpenFilter )
			{
				if ( m_bDriverInstalled )
				{
					// usb not connected
					m_errCode = E_USB_NOT_CONNECTED;
				}
				else
				{
					// driver not installed
					m_errCode = E_DRIVER_NOT_INSTALLED;
				}
				// this case, result = E_NOERROR
			}
			m_MSDriver.Close_Filter();
		}
	}
}
